<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE HTML>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>档案挂接</title>
    <style>
        #filePicker div:nth-child(2) {
            width: 100% !important;
            height: 100% !important;
        }

        /*#uploader .statusBar {*/
            /*bottom: -21rem;*/
        /*}*/

    </style>
</head>

<body class="hold-transition skin-blue sidebar-mini">
    <div id="showUploadModal" class="modal fade bs-example-modal-lg addUpdateInfo" role="dialog"
        aria-labelledby="myLargeModalLabel">
        <!--右侧图片上传区域-->
        <div id="uploader" class="wu-example" style="margin-top:30px;width:80%;height:80%;overflow-y:scroll;">
            <div class="queueList">
                <div id="dndArea" class="placeholder">
                    <div id="filePicker" class="webuploader-container">
                        <div class="webuploader-pick">点击选择文件</div>
                        <div id="rt_rt_1c9gfvk7sh9b1ptba23qr9vf71"
                            style="position: absolute; top: 0px; left: 448px; width: 168px; height: 44px; overflow: hidden; bottom: auto; right: auto;">
                            <input type="file" name="file" class="webuploader-element-invisible" multiple="multiple"
                                accept="application/pdf"><label
                                style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label>
                        </div>
                    </div>
                    <p>或将文件拖到这里，单次最多可选1000个</p>
                </div>
                <ul class="filelist"></ul>
            </div>
            <div class="statusBar" style="display:none;">
                <div class="progress" style="display: none;">
                    <span class="text">0%</span>
                    <span class="percentage" style="width: 0%;"></span>
                </div>
                <div class="info">共0个文件（0B），已上传0个文件</div>
                <div class="btns">
                    <div id="filePicker2" class="webuploader-container">
                        <div class="webuploader-pick">继续添加</div>
                        <div id="rt_rt_1c9gfvk811n911hue1tsp1nr2hlt6"
                            style="position: absolute; top: 0px; left: 0px; width: 1px; height: 1px; overflow: hidden;">
                            <input type="file" name="file" class="webuploader-element-invisible" multiple="multiple"
                                accept="application/pdf"><label
                                style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label>
                        </div>
                    </div>
                    <%-- data-id 当前挂载的与之对应的卷/件id data-type 挂载的文件类型 0：卷 1：件 --%>
                    <div id="uploadSubmit" class="uploadBtn state-pedding" data-id="" data-type="" data-tableId="">开始上传
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        // WebUploader实例
        var uploader;
        var $wrap = $('#uploader'),
            // 图片容器
            $queue = $('<ul class="filelist"></ul>')
                .appendTo($wrap.find('.queueList')),
            // 状态栏，包括进度和控制按钮
            $statusBar = $wrap.find('.statusBar'),
            // 文件总体选择信息。
            $info = $statusBar.find('.info'),
            // 上传按钮
            $upload = $wrap.find('.uploadBtn'),
            // 没选择文件之前的内容。
            $placeHolder = $wrap.find('.placeholder'),
            // 总体进度条
            $progress = $statusBar.find('.progress').hide(),
            // 添加的文件数量
            fileCount = 0,
            // 添加的文件总大小
            fileSize = 0,
            // 优化retina, 在retina下这个值是2
            ratio = window.devicePixelRatio || 1,
            // 缩略图大小
            thumbnailWidth = 110 * ratio,
            thumbnailHeight = 110 * ratio,
            // 可能有pedding, ready, uploading, confirm, done.
            state = 'pedding',
            // 所有文件的进度信息，key为file id
            percentages = {},
            supportTransition = (function () {
                var s = document.createElement('p').style,
                    r = 'transition' in s ||
                        'WebkitTransition' in s ||
                        'MozTransition' in s ||
                        'msTransition' in s ||
                        'OTransition' in s;
                s = null;
                return r;
            })();

        var stats;

        //关闭模态框销毁WebUploader，解决再次打开模态框时按钮越变越大问题
        $('#showUploadModal').on('hide.bs.modal', function () {
            if (fileCount != 0) {
                var files = uploader.getFiles();
                for (var index in files) {
                    uploader.onFileDequeued(files[index]);
                }
            }
            uploader.reset();
            var table = $("#uploadSubmit").attr("data-tableId");
            $('#' + table).bootstrapTable('refresh')
        });



        //开启模态框，初始化按钮信息
        $('#showUploadModal').on('show.bs.modal', function () {
            //自定义上传文件个数以及上传文件的地址
            var fileNum = $("#uploadSubmit").attr("data-fileNum");
            if(fileNum == 1){
                $("#filePicker2").hide();
            }else{
                $("#filePicker2").show();
            }
        });

        /*************************************** 文件上传 开始 *********************************************/
        jQuery(function () {
            var $ = jQuery;    // just in case. Make sure it's not an other libaray.
            if (!WebUploader.Uploader.support()) {
                $.alert({ title: '提示', content: 'eb Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器!', });
                throw new Error('WebUploader does not support the browser you are using.');
            }
            // 实例化
            uploader = WebUploader.create({
                pick: {
                    id: '#filePicker',
                    label: '点击选择文件'
                },
                dnd: '#uploader .queueList',
                paste: document.body,
                accept: {
                    title: 'files',
                    extensions: 'pdf',
                    mimeTypes: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        + ',application/pdf,image/*'
                },
                //{Boolean} [可选] [默认值：false] 设置为 true 后，不需要手动调用上传，有文件选择即开始上传
                // swf文件路径
                swf: '/resources/zheng-admin/plugins/webuploader-0.1.5/Uploader.swf',
                // {Selector} [可选] [默认值：false] 是否禁掉整个页面的拖拽功能，如果不禁用，图片拖进来的时候会默认被浏览器打开
                disableGlobalDnd: true,
                //{Boolean} [可选] [默认值：false] 是否要分片处理大文件上传
                chunked: false,
                server: '${basePath}/pcwindow/uploadFile',
                fileNumLimit: 1000,
                fileSizeLimit: 500000 * 1024 * 1024,    // 500000 M
                fileSingleSizeLimit: 500 * 1024 * 1024, // 500 M
                threads: 1, //上传并发数
                duplicate: true
            });

            //不管成功或者失败，文件上传完成时触发
            uploader.onUploadComplete = function (file, response) {
            };

            //当文件上传成功时触发
            uploader.onUploadSuccess = function (file, response) {
            };

            //当文件上传出错时触发
            uploader.onUploadError = function (file, response) {
            };

            // 添加“添加文件”的按钮，
            uploader.addButton({
                id: '#filePicker2',
                label: '继续添加'
            });

            uploader.onUploadProgress = function (file, percentage) {
                var $li = $('#' + file.id),
                    $percent = $li.find('.progress span');
                $percent.css('width', percentage * 100 + '%');
                percentages[file.id][1] = percentage;
                updateTotalProgress();
            };

            uploader.onFileQueued = function (file) {
                fileCount++;
                fileSize += file.size;
                if (fileCount === 1) {
                    $placeHolder.addClass('element-invisible');
                    $statusBar.show();
                }
                addFile(file);
                setState('ready');
                updateTotalProgress();
            };

            //移除队列
            uploader.onFileDequeued = function (file) {
                var unUpload = $("#unUpload").val();
                unUpload = parseInt(unUpload) - 1;
                $("#unUpload").val(unUpload);
                fileCount--;
                fileSize -= file.size;
                //根据前端插件ID寻找要移除的行
                var id = file.id;
                var ids = [];
                ids.push(id);
                //每移除一个重新对剩下的进行排序
                var order = $("#ord").val();
                order = parseInt(order) - 1;
                $("#ord").val(order);
                if (!fileCount) {
                    setState('pedding');
                }
                removeFile(file);
                updateTotalProgress();
            };

            uploader.on('all', function (type) {
                switch (type) {
                    case 'uploadFinished':
                        updateStatus("confirm");
                        $(".info").html();
                        break;
                }
            });
            uploader.onError = function (code) {

            };

            //接收服务器的数据
            uploader.on("uploadAccept", function (file, data) {
                if (data.code == "0") {
                    // 通过return false来告诉组件，此文件上传有错。
                    return false;
                } else {
                    return true;
                }
            });

            $upload.on('click', function () {
                var fileId = $("#uploadSubmit").attr("data-id");
                var fileType = $("#uploadSubmit").attr("data-type");
                var obj = new Object();
                //自定义上传文件个数以及上传文件的地址
                var fileNum = $("#uploadSubmit").attr("data-fileNum");
                var files = uploader.getFiles();
                //单一文件上传
                if (fileNum == 1) {
                    //如果文件长度非1个 提示
                    if (files.length == 1) {
                        uploader.options.server = '${basePath}/pcwindow/uploadSingleFile';
                    } else {
                        confirmEvent('当前为单一挂件，请保证上传的文件唯一！');
                        return;
                    }
                } else {
                    uploader.options.server = '${basePath}/pcwindow/uploadFile';
                }
                obj.fileId = fileId;
                obj.fileType = fileType;
                uploader.options.formData = obj;
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                if (state === 'ready') {
                    uploader.upload();
                } else if (state === 'paused') {
                    uploader.upload();
                } else if (state === 'uploading') {
                    uploader.stop();
                }
            });

            $info.on('click', '.retry', function () {
                uploader.retry();
            });
            $info.on('click', '.ignore', function () {
            });
            $upload.addClass('state-' + state);
            updateTotalProgress();
        });

        // 当有文件添加进来时执行，负责view的创建
        function addFile(file) {
            var unUpload = $("#unUpload").val();
            unUpload = parseInt(unUpload) + 1;
            $("#unUpload").val(unUpload);
            var order = $("#ord").val();
            //查询数据库目前最大顺序
            var total = $("#total").val();
            if ((total > 0) && (order == 1)) {
                order = parseInt(order) + parseInt(total);
            }
            var size = "";
            if ((file.size > 1000) && (file.size < 1000000)) {
                size = round(file.size / 1000, 2) + "kb";
            }
            if (file.size < 1000) {
                size = round(file.size / 1000, 2) + "kb";
            }
            if (file.size > 1000000) {
                size = round(file.size / 1000000, 2) + "mb";
            }
            var rows = [];
            rows.push({
                otName: file.name,
                otStrTwo: order,
                otStrFour: size,
                otStrThree: '1',
                otUrl: '',
                otStrFive: file.id
            });
            var order = parseInt(order) + 1;
            $("#ord").val(order);

            var $li = $('<li id="' + file.id + '" title="'+file.name+'">' +
                '<p class="title" style="word-break:break-all;white-space:normal;">' + file.name + '</p>' +
                '<p class="imgWrap"></p>' +
                '<p class="progress"><span></span></p>' +
                '</li>'),
                $btns = $('<div class="file-panel" ><span class="cancel">删除</span></div> ').appendTo($li),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find('p.imgWrap'),
                $info = $('<p class="error"></p>'),

                showError = function (code) {
                    switch (code) {
                        case 'exceed_size':
                            text = '文件大小超出';
                            break;

                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败,请重试';
                            break;
                    }
                    $info.text(text).appendTo($li);
                };

            if (file.getStatus() === 'invalid') {
                showError(file.statusText);
            } else {
                // @todo lazyload
                $wrap.text('预览中');
                uploader.makeThumb(file, function (error, src) {
                    if (error) {
                        $wrap.text('不能预览');
                        return;
                    }
                    var img = $('<img src="' + src + '">');
                    $wrap.empty().append(img);
                }, thumbnailWidth, thumbnailHeight);
                percentages[file.id] = [file.size, 0];
                file.rotation = 0;
            }

            file.on('statuschange', function (cur, prev) {
                if (prev === 'progress') {
                    $prgress.hide().width(0);
                } else if (prev === 'queued') {
                    $li.off('mouseenter mouseleave');
                    $btns.remove();
                }

                // 成功
                if (cur === 'error' || cur === 'invalid') {
                    showError(file.statusText);
                    percentages[file.id][1] = 1;
                } else if (cur === 'interrupt') {
                    showError('interrupt');
                } else if (cur === 'queued') {
                    percentages[file.id][1] = 0;
                } else if (cur === 'progress') {
                    $info.remove();
                    $prgress.css('display', 'block');
                } else if (cur === 'complete') {
                    $li.append('<span class="success"></span>');
                }

                $li.removeClass('state-' + prev).addClass('state-' + cur);
            });

            $li.on('mouseenter', function () {
                $btns.stop().animate({ height: 30 });
            });

            $li.on('mouseleave', function () {
                $btns.stop().animate({ height: 0 });
            });

            $btns.on('click', 'span', function () {
                var index = $(this).index(),
                    deg;

                switch (index) {
                    case 0:
                        uploader.removeFile(file);
                        return;
                    case 1:
                        file.rotation += 90;
                        break;

                    case 2:
                        file.rotation -= 90;
                        break;
                }
                if (supportTransition) {
                    deg = 'rotate(' + file.rotation + 'deg)';
                    $wrap.css({
                        '-webkit-transform': deg,
                        '-mos-transform': deg,
                        '-o-transform': deg,
                        'transform': deg
                    });
                } else {
                    $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                }
            });
            $li.appendTo($queue);
        }

        // 负责view的销毁
        function removeFile(file) {
            var $li = $('#' + file.id);
            delete percentages[file.id];
            updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        }

        function updateTotalProgress() {
            var loaded = 0,
                total = 0,
                spans = $progress.children(),
                percent;

            $.each(percentages, function (k, v) {
                total += v[0];
                loaded += v[0] * v[1];
            });
            percent = total ? loaded / total : 0;
            spans.eq(0).text(Math.round(percent * 100) + '%');
            spans.eq(1).css('width', Math.round(percent * 100) + '%');
            updateStatus("ready");
        }

        function updateStatus(state) {
            var text = ''
            if (state == 'ready') {
                text = '选中' + fileCount + '个文件，共' +
                    WebUploader.formatSize(fileSize) + '。';
            } else if (state == 'confirm') {
                stats = uploader.getStats();
                if (stats.uploadFailNum) {
                    text = '已成功上传' + stats.successNum + '个文件，' +
                        stats.uploadFailNum + '个文件上传失败，<a class="retry" href="#">重新上传</a>失败文件或<a class="ignore" href="#">忽略</a>'
                } else {
                    text = '共' + fileCount + '个（' +
                        WebUploader.formatSize(fileSize) +
                        '），已上传' + stats.successNum + '个';
                    //先远程刷新成功后然后再执行排序
                }

            } else {
                stats = uploader.getStats();
                text = '共' + fileCount + '个（' +
                    WebUploader.formatSize(fileSize) +
                    '），已上传' + stats.successNum + '个';

                if (stats.uploadFailNum) {
                    text += '，失败' + stats.uploadFailNum + '个';
                }
            }
            $info.html(text);
        }


        function setState(val) {
            if (val === state) {
                return;
            }
            $upload.removeClass('state-' + state);
            $upload.addClass('state-' + val);
            state = val;
            switch (state) {
                case 'pedding':
                    $placeHolder.removeClass('element-invisible');
                    $queue.parent().removeClass('filled');
                    $queue.hide();
                    $statusBar.addClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'ready':
                    $placeHolder.addClass('element-invisible');
                    $('#filePicker2').removeClass('element-invisible');
                    $queue.parent().addClass('filled');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'uploading':
                    $('#filePicker2').addClass('element-invisible');
                    $progress.show();
                    $upload.text('暂停上传');
                    break;

                case 'paused':
                    $progress.show();
                    $upload.text('继续上传');
                    break;

                case 'confirm':
                    $progress.show();
                    $upload.text('继续上传');
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if (stats.successNum) {
                    } else {
                        // 没有成功的文件，重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }
            updateStatus();
        }

        //保留小数
        function round(v, e) {
            var t = 1;
            for (; e > 0; t *= 10, e--);
            for (; e < 0; t /= 10, e++);
            return Math.round(v * t) / t;
        }

    </script>
</body>

</ht